package com.sqx.modules.errand.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.coupon.dao.TbCouponUserDao;
import com.sqx.modules.coupon.entity.TbCouponUser;
import com.sqx.modules.errand.dao.UserInfoDao;
import com.sqx.modules.errand.entity.ErrandEvaluate;
import com.sqx.modules.errand.entity.ErrandRedPacket;
import com.sqx.modules.errand.entity.Feedback;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.service.UserInfoService;
import com.sqx.modules.order.entity.Evaluate;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.service.CashOutService;
import com.sqx.modules.utils.VerifyIdCardUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, ErrandEvaluate> implements UserInfoService {

    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private CashOutService cashOutService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TbCouponUserDao tbCouponUserDao;

    @Override
    public UserEntity findUserInfoById(Long userId) {
        return userInfoDao.findUserInfoById(userId);
    }

    @Transactional
    @Override
    public Result certification(Long userId, UserEntity tbUser) {
        CommonInfo one = commonInfoService.findOne(260);
        log.error("1");
        if("是".equals(one.getValue())){
            String result = VerifyIdCardUtils.verifyIdCard(tbUser.getIdentityCardNumber(),tbUser.getUserName());
            log.error("2");
            if("ok".equals(result)){
                log.error("3");
                log.error("user:"+tbUser.toString());
                /*tbUser.setCheckCertification("1");
                userService.updateById(tbUser);*/
                UserEntity userById = userService.selectUserById(userId);
                UserEntity userEntity = userService.queryByPhone(tbUser.getPhone());
                if(userEntity!=null){
                    //todo 用户实名认证的时候，不管用户有没有两个账号，在这里会直接根据open_id删除小程序的账号，是不是应该加个判断？
                    userService.remove(new QueryWrapper<UserEntity>().eq("open_id",userById.getOpenId()));
                    userEntity.setOpenId(userById.getOpenId());
                    userEntity.setCheckCertification("1");
                    userEntity.setIdentityCardNumber(tbUser.getIdentityCardNumber());
                    userEntity.setUserName(tbUser.getUserName());
                    userEntity.setAuditTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    userService.updateById(userEntity);
                    return userService.getResult(userEntity);
                }else{
                    tbUser.setUserId(userId);
                    tbUser.setCheckCertification("1");
                    tbUser.setAuditTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    userService.updateById(tbUser);
                    return Result.success();
                }
            }else{
                return Result.error("您填写的信息有误，请检查后重试！");
            }
        }else{
            tbUser.setCheckCertification("0");
            userService.updateById(tbUser);
        }
        return Result.success();
    }

    @Transactional
    @Override
    public Result checkPhone(String openId,String phone,Integer userType){
        UserEntity userEntity = userService.queryByPhone(phone);
        if(userEntity!=null){
            userService.remove(new QueryWrapper<UserEntity>().eq("open_id",openId));
            userEntity.setOpenId(openId);
            userService.updateById(userEntity);
            return userService.getResult(userEntity);
        }else{
            userEntity = userService.queryByOpenId(openId,userType);
            userEntity.setPhone(phone);
            userService.updateById(userEntity);
            return Result.success();
        }
    }

    @Transactional
    @Override
    public Result riderCertification(Long userId, UserEntity tbUser) {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        CommonInfo one = commonInfoService.findOne(260);
        if("是".equals(one.getValue())){
            String result = VerifyIdCardUtils.verifyIdCard(tbUser.getIdentityCardNumber(),tbUser.getUserName());
            if("ok".equals(result)){
                int i = userInfoDao.certification(userId,tbUser.getPhone(), tbUser.getUserName(), tbUser.getIdentityCardNumber(),
                        tbUser.getIdentityCardFront(),tbUser.getIdentityCardVerso(),tbUser.getSelfIdentityCard(), format,
                        tbUser.getCheckNumber(), tbUser.getCashDeposit());
                UserEntity user=new UserEntity();
                user.setCheckCertification("1");
                user.setUserId(tbUser.getUserId());
                user.setAuditTime(format);
                userService.updateById(user);
                return Result.success();
            }else{
                return Result.error("您填写的信息有误，请检查后重试！");
            }
        }
        int i = userInfoDao.certification(userId,tbUser.getPhone(), tbUser.getUserName(), tbUser.getIdentityCardNumber(), tbUser.getIdentityCardFront(),tbUser.getIdentityCardVerso(),tbUser.getSelfIdentityCard(), format, tbUser.getCheckNumber(), tbUser.getCashDeposit());
        return Result.success();
    }

    @Override
    public Result updateUserInfoById(UserEntity tbUser) {
        int i = userInfoDao.updateUserInfoById(tbUser.getNickName(), tbUser.getAvatar(), tbUser.getPhone(), tbUser.getCashQrCode(), tbUser.getUserId());
        return Result.success();
    }

    @Override
    public Result userFeedback(Long userId, Feedback feedback) {
        userInfoDao.userFeedback(feedback.getFeedbackType(),userId, feedback.getUserEmail(), feedback.getFeedbackScore(), feedback.getFeedbackMessage(),
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return Result.success();
    }

    @Override
    public Result findIncome(Long userId) {
        HashMap hashMap = new HashMap();
        //今日收益
        BigDecimal incomeday = userInfoDao.findIncomeday(userId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        BigDecimal prepayMoneyday = userInfoDao.findPrepayMoneyday(userId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        BigDecimal subtract = incomeday.subtract(prepayMoneyday);
        //本月收益
        BigDecimal incomemonth = userInfoDao.findIncomemonth(userId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        BigDecimal prepayMoneymonth = userInfoDao.findPrepayMoneymonth(userId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        BigDecimal subtract1 = incomemonth.subtract(prepayMoneymonth);
        //累计收益
        BigDecimal incomesum = userInfoDao.findIncomesum(userId);
        BigDecimal prepayMoneysum = userInfoDao.findPrepayMoneysum(userId);
        BigDecimal subtract2 = incomesum.subtract(prepayMoneysum);
        //今日订单数
        int indentCount = userInfoDao.findIndentCount(userId, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        hashMap.put("incomeday",subtract);
        hashMap.put("incomemonth",subtract1);
        hashMap.put("incomesum",subtract2);
        hashMap.put("indentCount",indentCount);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result findBalance(Long userId) {
        double balance = userInfoDao.findBalance(userId);
        return Result.success().put("data", balance);
    }

    @Override
    public Result findCashDeposit(Long userId) {
        double cashDeposit = userInfoDao.findCashDeposit(userId);
        return Result.success().put("data", cashDeposit);
    }

    @Override
    public Result findMoneyDetails(Long userId,Integer page,Integer limit, Integer classify) {
        IPage<UserMoneyDetails> moneyDetails = userInfoDao.findMoneyDetails(new Page<>(page,limit),userId, classify);
        return Result.success().put("data", new PageUtils(moneyDetails));
    }

    @Override
    public Result findEvaluate(Long userId, Integer page, Integer limit, String satisfactionFlag) {
        Page<ErrandEvaluate> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findEvaluate(pages, userId, satisfactionFlag));
        return Result.success().put("data", pageUtils);
    }

    @Transactional
    @Override
    public Result getNewUserRedPacket(Long userId) {
        //查看该用户是否是新用户
        UserEntity userInfoById = userInfoDao.findUserInfoById(userId);
        if(1==userInfoById.getNewUserFlag()){
            ErrandRedPacket redPacket = new ErrandRedPacket();
            //如果是新用户，则可以领取新人红包
            //红包数额
            CommonInfo one = commonInfoService.findOne(253);
            BigDecimal redPacketAmount = new BigDecimal(one.getValue());
            //红包数量
            CommonInfo one1 = commonInfoService.findOne(254);
            Integer integer = Integer.valueOf(one1.getValue());
            //红包过期时间
            CommonInfo one2 = commonInfoService.findOne(255);
            Integer integer1 = Integer.valueOf(one2.getValue());

            Date date = new Date();
            Date addDate = addDate(integer1);
            String expirationTime = new SimpleDateFormat("yyyy-MM-dd").format(addDate);
            String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            redPacket.setRedPacketType("0");
            redPacket.setRedPacketTitle("跑腿专用红包");
            redPacket.setMinimumAmount(new BigDecimal(0));
            for(int i = 0;i<integer; i++){
                userInfoDao.addRedPacket(userId, redPacket.getRedPacketType(), redPacket.getMinimumAmount(), redPacketAmount,
                        redPacket.getRedPacketTitle(), expirationTime, createTime);
            }
            //修改用户为非新用户
            int i = userInfoDao.updateOldUser(userId);
            return Result.success();
        }
        return Result.error("本福利仅新用户可领取！");
    }

    public static Date addDate (int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, num);
        Date date = calendar.getTime();
        return date;
    }

    @Override
    public Result getNewUserRedPacketWm(Long userId) {
        //查看该用户是否是新用户
        UserEntity userInfoById = userInfoDao.findUserInfoById(userId);
        if(1==userInfoById.getNewUserFlagWm()){
            TbCouponUser tbCouponUser = new TbCouponUser();
            //如果是新用户，则可以领取新人红包
            //红包数额
            CommonInfo one = commonInfoService.findOne(319);
            BigDecimal money = new BigDecimal(one.getValue());
            //红包数量
            CommonInfo one1 = commonInfoService.findOne(320);
            Integer num = Integer.valueOf(one1.getValue());
            //红包过期时间
            CommonInfo one2 = commonInfoService.findOne(321);
            Integer endTime = Integer.valueOf(one2.getValue());
            //红包封面
            CommonInfo one3 = commonInfoService.findOne(322);
            String couponPicture = one3.getValue();
            Date addDate = addDate(endTime);
            tbCouponUser.setUserId(userId);
            tbCouponUser.setCouponName("新用户专享红包");
            tbCouponUser.setCouponPicture(couponPicture);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date());
            tbCouponUser.setCreateTime(format);
            tbCouponUser.setExpirationTime(simpleDateFormat.format(addDate));
            tbCouponUser.setMinMoney(BigDecimal.valueOf(0));
            tbCouponUser.setGoodsType("0");
            tbCouponUser.setMoney(money);
            tbCouponUser.setStatus(0);
            tbCouponUser.setEndTime(String.valueOf(endTime));
            for(int i = 0;i<num; i++){
                tbCouponUserDao.insert(tbCouponUser);
            }
            //修改用户为非新用户
            userInfoDao.updateNewUserFlagWm(userId);
            return Result.success();
        }
        return Result.error("本福利仅新用户可领取！");
    }

    @Override
    public Result updateCoordinate(Long userId, double lng, double lat) {
        userInfoDao.updateCoordinate(userId, lng, lat);
        return Result.success();
    }

    @Override
    public Result updateOnLine(Long userId, Integer onLineFlag) {
        userInfoDao.updateOnLine(userId, onLineFlag);
        return Result.success();
    }

    @Override
    public Result rankingList(Integer page, Integer limit, String address, String date, String dateType) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(userInfoDao.rankingList(pages, address, date, dateType));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result bannedFlag(Long userId) {

        UserEntity userEntity = userDao.selectById(userId);
        return Result.success().put("data", userEntity.getStatus());
    }

    @Override
    public Result selectCashDeposit(Long userId, Integer page, Integer limit, Integer classify) {
        Page<UserMoneyDetails> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(userInfoDao.selectCashDeposit(pages, userId, classify));
        return Result.success().put("data", pageUtils);
    }

}
